package com.yonyou.sto.common.domain;

import org.apache.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author Aegon Targaryen
 * @date Created in 2020/10/19 15:26
 * @description: TODO
 */
public class DownloadFile {

    /**
     * inputstream转Byte[]
     *
     * @param inStream
     * @return
     * @throws IOException
     */
    public static byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        return swapStream.toByteArray();
    }

    /**
     * 下载
     *
     * @param response
     * @param request
     * @param filename
     * @param fileData
     * @return
     */
    public static boolean downloadFile(HttpServletResponse response,
                                       HttpServletRequest request, String filename, byte[] fileData) {
        try {
            OutputStream myout = null;
            // 检查时候获取到数据
            if (fileData == null) {
                response.sendError(HttpStatus.SC_NOT_FOUND);
                return false;
            }
            try {
                if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                    filename = new String(filename.getBytes("GBK"), "iso-8859-1");
                } else {
                    filename = URLEncoder.encode(filename, "utf-8");
                }
                response.setContentType("multipart/form-data");
                /*response.setContentType("multipart/form-data;charset=utf-8");*/
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                // 写明要下载的文件的大小
                response.setContentLength(fileData.length);
                // 从response对象中得到输出流,准备下载
                myout = response.getOutputStream();
                myout.write(fileData);
                myout.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (myout != null) {
                    try {
                        myout.close();
                    } catch (Exception e) {
                    }
                }
            }
        } catch (IOException e) {
            return false;
        }
        return true;
    }


}
